package com.work.yshop.ui.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.work.yshop.R;
import com.work.yshop.model.Article;
import com.work.yshop.mvp.contract.ArticleContract;
import com.work.yshop.mvp.presenter.ArticlePresenter;
import com.work.yshop.provider.ArticleProvider;
import com.work.yshop.utils.UserSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 添加文章页面
 */
public class AddArticleActivity extends AppCompatActivity implements ArticleContract.View {

    private static final String TAG = "AddArticleActivity";
    private Toolbar toolbar;
    private EditText etTitle;
    private EditText etContent;
    private Spinner spCategory;
    private ImageView ivCover;
    private Button btnSave;
    
    private String[] categories = {"种植技术", "病虫防治", "农业科学", "视频教学"};
    private String imageUrl = "https://images.pexels.com/photos/2132171/pexels-photo-2132171.jpeg"; // 默认图片URL
    
    private ArticleContract.Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_article);
        
        // 初始化Presenter
        presenter = new ArticlePresenter(this);
        ((ArticlePresenter) presenter).attachView(this);
        
        initViews();
        setupToolbar();
        setupCategorySpinner();
        setupListeners();
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        spCategory = findViewById(R.id.sp_category);
        ivCover = findViewById(R.id.iv_cover);
        btnSave = findViewById(R.id.btn_save);
        
        // 设置封面点击事件
        ivCover.setOnClickListener(v -> {
            // 在实际应用中，这里应该打开图片选择器
            Toast.makeText(AddArticleActivity.this, "选择封面图片", Toast.LENGTH_SHORT).show();
        });
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("发布文章");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
    }
    
    private void setupCategorySpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCategory.setAdapter(adapter);
    }
    
    private void setupListeners() {
        btnSave.setOnClickListener(v -> publishArticle());
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add_article, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        } else if (id == R.id.action_publish) {
            publishArticle();
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    private void publishArticle() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        String category = spCategory.getSelectedItem().toString();
        
        // 验证输入
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (content.isEmpty()) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setCategory(category);
        article.setAuthor(UserSession.getInstance().getUsername());
        
        // 设置发布日期（当前日期）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        article.setPublishDate(sdf.format(new Date()));
        
        // 设置初始阅读量
        article.setViewCount(0);
        
        // 设置图片URL
        article.setImageUrl(imageUrl);
        
        // 生成摘要（使用内容的前50个字符）
        String summary = content.length() > 50 ? content.substring(0, 50) + "..." : content;
        article.setSummary(summary);
        
        // 使用Presenter保存文章
        presenter.publishArticle(article);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
    }
    
    // ArticleContract.View接口实现
    @Override
    public void showLoading() {
        // 可以实现加载对话框
    }
    
    @Override
    public void hideLoading() {
        // 可以隐藏加载对话框
    }
    
    @Override
    public void showArticles(List<Article> articles) {
        // 不需要实现
    }
    
    @Override
    public void showEmptyView() {
        // 不需要实现
    }
    
    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void showPublishResult(boolean success, String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        
        if (success) {
            // 设置结果并返回
            setResult(RESULT_OK);
            finish();
        }
    }
    
    @Override
    public Context getContext() {
        return this;
    }
} 